package com.ciccwm.auth.filter;

import com.ciccwm.auth.dubbo.OAuth2DubboService;
import com.ciccwm.core.exception.UnauthorizedException;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;

@Activate(group = {CommonConstants.PROVIDER}, order = -9900)
@RequiredArgsConstructor
public class DubboAuthFilter implements Filter {

    private final JwtDecoder jwtDecoder;

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String token = RpcContext.getServiceContext().getAttachment("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new UnauthorizedException("Invalid or missing token");
        }

        try {
            jwtDecoder.decode(token.substring(7));
            return invoker.invoke(invocation);
        } catch (JwtException e) {
            throw new UnauthorizedException("Invalid token: " + e.getMessage());
        }
    }
}
